<?php
    /*  
    TextImage.class
    
    Copyright (C) 2009  Maik Kellerhals

    TextImage is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    TextImage is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
  
    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
    */

//////////////////////////////////////////////
// Class TextImage v. 1.0   //////////////////
//////////////////////////////////////////////
// Syntax:                                  //
// [Initialisation]                         //
//  $xyz = new TextImage();                 //
// [Customise Settings]                     //
//  $xyz->imageFolder = '/textImagePics/';  //
//  $xyz->fontName    = $_REQUEST[font];    //
//  ...                                     //
// [Call]                                   //
//  $xyz->imgTxt("Text to be shown");       //
//////////////////////////////////////////////
// Remarks:                                 //
// - Works with TrueType and OpenType Fonts //
// - Depending on the server-configuration  //
//   the font files need to be copied to    //
//   /usr/shared/fonts/truetype             //
//   in order for the Class to work.        //
//////////////////////////////////////////////
/////////////// Maik Kellerhals, 23.04.2009 //
//////////////////////////////////////////////


class TextImage {
    
    // global settings
    private $currentTime;      // variable for current timestamp
    public $delTime = '10000'; // time in seconds from the last access to 
                               // an imagefile to its deletion
                               // (1 week = 604800 seconds)

    // general display-settings
    public $imageFolder  = '/bilder/';  // path to the folder in which the 
                                        // images should be stored (must exist)
    public $fontName     = 'arial.ttf'; // path to the font file (.ttf or .otf)
    public $fontSize     = 20;          // font size in pixels
    public $fontColor    = '000000';    // font color (hex)
    public $bgColor      = 'FFFFFF';    // background color (hex)
    
    public $outputType   = 'img';       // type of output 
                                        //   'return' = no output 
                                        //              (return of URL only) 
                                        //      'url' = URL-Output
                                        //      'img' = <img>-tag (standard) 
                                        //      'div' = <div>-tag
                                        //        'a' = <a>-tag (Hyperlink)
    public $linkURL      = '#';         // URL, only for outputType 'a'
    public $linkTarget   = '_self';     // target for link, 
                                        // only for outputType 'a'
    public $linkClass    = '';          // CSS-Class to be used with the Link
        
    public $cssHover     = false;       // if true, a double image for 
                                        // CSS hovering will be created
    public $fontColor2   = 'FF0000';    // text color for lower half of 
                                        // hover-image (mouse over)
    public $bgColor2     = 'FFFFFF';    // background color for lower half 
                                        // of hover-image (mouse over)
    
    // settings for custom image-height (for consistant text positioning)
    public $customHeight = 0;           // custom height for image (0 = auto)
    public $customOffset = 0;           // distance from lower border of the 
                                        // image to the baseline of the text
    
    // info-variables (are filled on each call of imgTxt)
    public $filePath;      // path to the created image
    public $width;         // width of the created image in pixels
    public $height;        // height of the created image in pixels
    public $regenerated;   // is set to true if the image had to be generated
    
    // constructor
    function __construct() {
    
        // get current timestamp
        $this->currentTime = time();
        
        // CSS for hover-effect (preferably initialised in head-area)
        echo "\n\r" . '<!-- CSS-Code created by TextImage-class -->' . "\n";
        echo '    <style type="text/css">' . "\n";
        echo '        div.textImageHover:hover, a.textImageHover:hover '.
             '{background-position: bottom;}' . "\n";
        echo '    </style>' . "\n";
        echo '<!-- end of TextImage-CSS -->' . "\n\n";
    }
    
    // main function, creates and/or displays image
    public function imgTxt ($text = 'no text defined') 
    {           
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].$this->fontName)) {
            echo '<br /><span style="color:red;background-color:white;">'.
                 '<b>Fehler in PHP-Klasse TextImage:</b> Schriftdatei <b>' 
                 . $this->fontName 
                 . '</b> ist nicht vorhanden!</span><br />';
        } else {
    
            // creation of image-filename
            $imgUrl = preg_replace('/[^a-zA-Z0-9_-]/u', '_', $text);
            $this->filePath = $this->imageFolder.substr($imgUrl, 0, 10) 
                            . substr(md5($text), 0, 5) 
                            . strtr(substr($this->fontName, 0, -4), '/', '_')
                            . $this->fontSize 
                            . $this->fontColor 
                            . $this->cssHover 
                            . $this->bgColor 
                            . $this->fontColor2 
                            . $this->bgColor2
                            . $this->customHeight
                            . $this->customOffset
                            . '.png';
            
            // if path is from root, url needs to be adjusted
            if (substr($this->imageFolder, 0, 1) == '/' ) {
                $imgUrl = $_SERVER['DOCUMENT_ROOT'].$this->filePath;
            } else {
                $imgUrl = $this->filePath;
            }
            
            // check if file already exists. If not, a new one will be generated
            if (!file_exists($imgUrl)) {
                
                // create dummy-image for measurement only
                $im0 = ImageCreateTrueColor (1, 1);
                $textBox = ImageTTFText($im0, 
                                        $this->fontSize, 
                                        0, 
                                        $this->fontSize*4, 
                                        $this->fontSize*4, 
                                        0xFFFFFF, 
                                        $_SERVER['DOCUMENT_ROOT'].$this->fontName, 
                                        $text);
                
                // get distances from extremes to the start positions
                $distX = $this->fontSize * 4 - $textBox[0];
                
                // set width of final image
                $this->width = $textBox[2] - $textBox[0];
                
                if ($this->customHeight) {
                    $this->height = $this->customHeight;
                    $distY = $this->customOffset;
                } else {
                    $this->height = $textBox[1] - $textBox[7];
                    $distY = $textBox[1] - $this->fontSize * 4;
                }
                
                // create final image, in double height if CSS-hover is activated
                if ($this->cssHover) {
                    $im = ImageCreateTrueColor ($this->width, $this->height*2);
                    imageFill($im, 0, 0, hexdec($this->bgColor));
                    imageTTFText ($im, 
                                  $this->fontSize, 
                                  0, 
                                  $distX, 
                                  $this->height-$distY, hexdec($this->fontColor), 
                                  $_SERVER['DOCUMENT_ROOT'].$this->fontName, 
                                  $text);
                    imagefilledrectangle($im, 
                                         0, 
                                         $this->height, 
                                         $this->width, 
                                         $this->height*2, 
                                         hexdec($this->bgColor2));
                    imageTTFText ($im, 
                                  $this->fontSize, 
                                  0, 
                                  $distX, 
                                  $this->height*2-$distY, hexdec($this->fontColor2), 
                                  $_SERVER['DOCUMENT_ROOT'].$this->fontName, 
                                  $text);
                } else {
                    $im = ImageCreateTrueColor ($this->width, $this->height);
                    imageFill($im, 0, 0, hexdec($this->bgColor));
                    imageTTFText ($im, 
                                  $this->fontSize, 
                                  0, 
                                  $distX, 
                                  $this->height-$distY, 
                                  hexdec($this->fontColor), 
                                  $_SERVER['DOCUMENT_ROOT'].$this->fontName, 
                                  $text);       
                }
                
                // save image
                imagePNG ($im, $imgUrl);
                
                $this->height *= 2;
                $this->regenerated = true;
                
                // delete images who were accessed last more than $delTime seconds ago
                foreach (glob($_SERVER['DOCUMENT_ROOT'].$this->imageFolder . "*.png") as $filename) {
                    $fileTime = fileatime($filename);
                    if ($fileTime + $this->delTime < $this->currentTime) {
                        unlink($filename);
                    }
                }
                
            } else {
                // if the image already exists, the data needs to be extracted
                $size = getimagesize($imgUrl);
    			$this->width = (int) $size[0];
    			$this->height = (int) $size[1];	
                
                $this->regenerated = false;
            }
            
            // final output
            switch ($this->outputType) {
            
            case 'return':
                return $this->filePath;
                break;
                
            case 'url':
                echo $this->filePath;
                break;
                
            case 'img':
                echo '<img src="'.$this->filePath.'" class="'.$this->linkClass.'">';
                break;
                
            case 'div':
                if ($this->cssHover || $this->regenerated == true) {
                    echo '<div class="textImageHover" style="background-image:url(' 
                                    . $this->filePath 
                                    . ');width:' 
                                    . $this->width 
                                    . 'px;height:' 
                                    . $this->height / 2 
                                    . 'px;"></div>';
                } else {
                    echo '<div class="textImageHover" style="background-image:url(' 
                                    . $this->filePath 
                                    . ');width:' 
                                    . $this->width 
                                    . 'px;height:' 
                                    . $this->height 
                                    . 'px;"></div>';
                }
                break;
            
            case 'a':
                if ($this->cssHover || $this->regenerated == true) {
                    echo '<a href="'. $this->linkURL . '" target="' 
                                    . $this->linkTarget 
                                    . '" class="textImageHover '
                                    . $this->linkClass
                                    . '" style="background-image:url(' 
                                    . $this->filePath 
                                    . ');width:' 
                                    . $this->width 
                                    . 'px;height:' 
                                    . $this->height / 2 
                                    . 'px;display:block;">&nbsp;</a>';
                } else {
                    echo '<a href="'. $this->linkURL . '" target="' 
                                    . $this->linkTarget 
                                    . '" class="textImageHover '
                                    . $this->linkClass
                                    . '" style="background-image:url(' 
                                    . $this->filePath 
                                    . ');width:' 
                                    . $this->width 
                                    . 'px;height:' 
                                    . $this->height 
                                    . 'px;display:block;">&nbsp;</a>';
                }
                break;
                
            }
        }
    }
}
/////////////////////////
// END class TextImage //
/////////////////////////
